package com.onvifdemo.listener;

import be.teletask.onvif.listeners.OnvifResponseListener;
import be.teletask.onvif.models.OnvifDevice;
import be.teletask.onvif.responses.OnvifResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.onvifdemo.Entity.Common;
import com.onvifdemo.dto.DeviceInfo;
import com.onvifdemo.util.IsXmlUtil;
import com.onvifdemo.util.XmlToJsonUtils;
import org.apache.log4j.Logger;

import java.util.concurrent.CountDownLatch;

public class MyResponseListener implements OnvifResponseListener {


    /* (non-Javadoc)
     * @see be.teletask.onvif.listeners.OnvifResponseListener#onResponse(be.teletask.onvif.models.OnvifDevice, be.teletask.onvif.responses.OnvifResponse)
     */
    public void onResponse(OnvifDevice onvifDevice, OnvifResponse response) {
        // TODO Auto-generated method stub
        // System.out.println("response监听器返回的xml————》" + response.getXml());
        if (null != response) {
            getNtp(onvifDevice, response.getXml());
        } else {
            System.out.println("ntp 监听器返回的response null");
        }
        Common.cdlNtp = new CountDownLatch(1);
        Common.cdlNtp.countDown();

    }

    /* (non-Javadoc)
     * @see be.teletask.onvif.listeners.OnvifResponseListener#onError(be.teletask.onvif.models.OnvifDevice, int, java.lang.String)
     */
    public void onError(OnvifDevice onvifDevice, int errorCode, String errorMessage) {

        System.out.println(onvifDevice.getHostName() + "ntp response错误信息" + errorMessage);

        String hostName = onvifDevice.getHostName().substring(onvifDevice.getHostName().lastIndexOf("/") + 1);
        String deviceIP = hostName;
        if (Common.deviceNtpMap.containsKey(deviceIP)) {

            DeviceInfo haveDevice = Common.deviceNtpMap.get(deviceIP);

            haveDevice.setErrorCode(errorCode);
            if (IsXmlUtil.isXmlDocument(errorMessage)) {
                JSONObject jsobj = XmlToJsonUtils.xmlToJson(errorMessage);
                if (null != jsobj) {

                    if (errorMessage.contains("body") && errorMessage.contains("h2")) {

                        String requestResut = jsobj.getString("p");
                        String h2 = jsobj.getString("h2");
                        haveDevice.setErrorMsg(requestResut + "-->" + h2);

                    }

                    if (null != jsobj.getJSONObject("Fault")) {
                        String errorText = jsobj.getJSONObject("Fault").getJSONObject("Detail").getString("Text");
                        haveDevice.setErrorMsg(errorText);
                    }
                }
            } else {
                haveDevice.setErrorMsg(errorMessage);
            }

            // haveDevice.setErrorMsg(errorMessage);

        } else {
            DeviceInfo device = new DeviceInfo();

            device.setDeviceIP(deviceIP);
            device.setErrorCode(errorCode);
            if (IsXmlUtil.isXmlDocument(errorMessage)) {
                JSONObject jsobj = XmlToJsonUtils.xmlToJson(errorMessage);
                if (null != jsobj) {
                    if (errorMessage.contains("body") && errorMessage.contains("h2")) {

                        String requestResut = jsobj.getString("p");
                        String h2 = jsobj.getString("h2");
                        device.setErrorMsg(requestResut + "-->" + h2);

                    }
                    if (null != jsobj.getJSONObject("Fault")) {
                        String errorText = jsobj.getJSONObject("Fault").getJSONObject("Reason").getString("Text");
                        device.setErrorMsg(errorText);
                    }
                }
            } else {
                device.setErrorMsg(errorMessage);
            }

            Common.deviceNtpMap.put(deviceIP, device);
        }

        Common.cdlNtp.countDown();
    }

    /**
     * 获取时间或ntp
     * 
     * @param xml
     * @return
     */
    private void getNtp(OnvifDevice onvifDevice, String xml) {

        String hostName = onvifDevice.getHostName().substring(onvifDevice.getHostName().lastIndexOf("/") + 1);
        String deviceIP = hostName;

        DeviceInfo myDevice = new DeviceInfo();
        myDevice.setDeviceIP(deviceIP);

        if (xml.contains("<tds:GetNTPResponse>")) {
            System.out.println(onvifDevice.getHostName() + "ntp得到的xml" + xml);

            String ntpIP = "";
            JSONObject json = XmlToJsonUtils.xmlToJson(xml);

            if (xml.contains("body") && xml.contains("h2")) {

                String requestResut = json.getString("p");
                String h2 = json.getString("h2");
                myDevice.setErrorMsg(requestResut + "-->" + h2);

            } else {
                JSONObject getNTPResponse = json.getJSONObject("GetNTPResponse");

                JSONObject NTPInformation = getNTPResponse.getJSONObject("NTPInformation");
                boolean FromDHCP = NTPInformation.getBoolean("FromDHCP");
                Object NTPManual = NTPInformation.get("NTPManual");

                if (NTPManual instanceof JSONArray) {
                    JSONArray NTPManualArray = (JSONArray)NTPManual;
                    ntpIP = NTPManualArray.getJSONObject(0).getString("IPv4Address");
                } else if (NTPManual instanceof JSONObject) {
                    JSONObject ntpManuaObj = (JSONObject)NTPManual;
                    ntpIP = ntpManuaObj.getString("IPv4Address");
                    // logger.info("解析得到的ntpIP:" + ntpIP);
                }

                // 封装设备ntp服务器
                myDevice.setNtpIp(ntpIP);
            }

            addDevcieToMap(myDevice);
        }

    }

    /**
     * 
     * @param device
     *            操作标志（时间、ntp）
     */
    private void addDevcieToMap(DeviceInfo device) {

        Common.deviceNtpMap.put(device.getDeviceIP(), device);
    }

}
